package com.yiwei.zxp.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yiwei.zxp.Application;
import com.yiwei.zxp.BussinessMainActivity;
import com.yiwei.zxp.R;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.LoginBean;
import com.yiwei.zxp.api.bean.RegisterBean;
import com.yiwei.zxp.api.bean.RegisterCheckBean;
import com.yiwei.zxp.api.bean.ResetPassBean;
import com.yiwei.zxp.api.bean.SmsSendBean;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.constant.Const;
import com.yiwei.zxp.constant.UserInfoGlobal;
import com.yiwei.zxp.util.Dialog;
import com.yiwei.zxp.util.MD5;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.PreferenceUtils;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.UI;
import com.yiwei.zxp.util.Util;
import com.yiwei.zxp.view.V19FrameLayout;

import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import butterknife.Unbinder;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class RegisterActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.txt_info)
    TextView txtInfo;
    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.layout_step_one)
    LinearLayout layoutStepOne;
    @BindView(R.id.edit_code)
    EditText editCode;
    @BindView(R.id.btn_code_clear)
    ImageView btnCodeClear;
    @BindView(R.id.btn_send_code)
    TextView btnSendCode;
    @BindView(R.id.layout_step_two)
    LinearLayout layoutStepTwo;
    @BindView(R.id.edit_pass_new)
    EditText editPassNew;
    @BindView(R.id.btn_pass_clear)
    ImageView btnPassClear;
    @BindView(R.id.btn_pass_visible)
    ImageView btnPassVisible;
    @BindView(R.id.txt_pass_tips)
    TextView txtPassTips;
    @BindView(R.id.layout_step_three)
    LinearLayout layoutStepThree;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    private String verify_token;
    private String self_phone;
    private final String STEP_ONE = "点击验证";
    private final String STEP_TWO = "下一步";
    private final String STEP_THREE = "完成";
    private Unbinder unbiner;
    private boolean isVisible = false;
    private boolean isSendCode = true;
    private int step = 0;
    private static final int TIME = 60 * 1000;  //验证码倒计时时间
    private CountDownTimer timer = new CountDownTimer(TIME, 1000) {

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onTick(long millisUntilFinished) {
            btnSendCode.setText("重新获取" + (millisUntilFinished / 1000) + "s");
            if (isSendCode) {
                isSendCode = false;
                btnSendCode.setEnabled(false);
                btnSendCode.setBackgroundResource(R.drawable.btn_send_code_uncheck);
                btnSendCode.setTextColor(0xFFFFFFFF);
            }

        }

        @Override
        public void onFinish() {
            isSendCode = true;
            resetBtn();
        }
    };

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void resetBtn() {
        if (timer != null) timer.cancel();
        btnSendCode.setEnabled(true);
        btnSendCode.setText("发送验证码");
        btnSendCode.setTextColor(0xFFFF0030);
        btnSendCode.setBackgroundResource(R.drawable.btn_send_code_check);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        txtTitle.setText("新用户注册");
        txtRight.setText("客服");
        txtRight.setVisibility(View.VISIBLE);
        String verify_token = getIntent().getStringExtra("verify_token");
        String phone = getIntent().getStringExtra("phone");
        if (!TextUtils.isEmpty(verify_token) && !TextUtils.isEmpty(phone)) {
            this.self_phone = phone;
            this.verify_token = verify_token;
            editPhone.setText(phone);
            btnSubmit.setText("下一步");
            layoutStepTwo.setVisibility(View.GONE);
            layoutStepThree.setVisibility(View.VISIBLE);
        }
    }

    public void getSmsSend(String phone) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        SmsSendBean bean = new SmsSendBean();
        bean.phone = phone;
        Api.api_service.getRegisterSend(bean).compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    this.self_phone = phone;
                    timer.start();
                    ToastUtil.makeText(this, "发送成功");
                    btnSubmit.setText(STEP_TWO);
                    layoutStepOne.setVisibility(View.GONE);
                    layoutStepTwo.setVisibility(View.VISIBLE);
                });
    }

    public void getSmsCheck(String phone, String code) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        RegisterCheckBean bean = new RegisterCheckBean();
        bean.phone = phone;
        bean.verify_code = code;
        Api.api_service.getRegisterCheck(bean).compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    resetBtn();
                    this.verify_token = result.datas.verify_token;

                    ToastUtil.makeText(this, "验证成功");
                    btnSubmit.setText(STEP_THREE);
                    layoutStepTwo.setVisibility(View.GONE);
                    layoutStepThree.setVisibility(View.VISIBLE);
                });
    }

    public void getRegister(String verify_token, String pass) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        RegisterBean bean = new RegisterBean();
        bean.verify_token = verify_token;
        bean.password = MD5.getMD5str(pass);
        Api.api_service.getRegister(bean).compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
//                    ToastUtil.makeText(this, "注册成功");
//                    finish();
                    getLogin(self_phone, pass);
                });
    }

    public void getLogin(String username, String password) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        LoginBean bean = new LoginBean();
        bean.username = username;
        bean.password = MD5.getMD5str(password);
        Api.api_service.getLogin(bean).compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    Set<String> tagSet = new LinkedHashSet<String>();
                    // tagSet.add(model.getData().getUser_name());
                    tagSet.add(result.datas.mobile);
                    JPushInterface.setAliasAndTags(getApplicationContext(), result.datas.mobile + "", tagSet, new TagAliasCallback() {
                        @Override
                        public void gotResult(int i, String s, Set<String> set) {
                            //  Log.i("", i + s + "       " + set.toString());
//                                ToastUtil.makeText(getApplicationContext(), i+"   "+s+"     "+set.toString(), Toast.LENGTH_SHORT).show();
                            switch (i) {
                                case 0:
                                    Log.i("", i + s + "       " + set.toString());
                                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                                    break;
                                case 6002:
                                    Log.i("6002", "60002");
                                    // 延迟 60 秒来调用 Handler 设置别名
                                    break;
                                default:
                                    Log.i("6002", "default");
                            }
                        }

                    });
                    UserInfoGlobal.saveLoginInfo(result.datas);
//                    ToastUtil.makeText(this, "注册成功");
                    Util.startActivity(this, RegisterSetRefereeActivity.class);
                    finish();
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        unbiner.unbind();
        unbiner = null;
    }

    @OnTextChanged(R.id.edit_phone)
    void afterTextChanged(Editable s) {
        if (TextUtils.isEmpty(UI.toString(editPhone))) {
            btnSubmit.setSelected(false);
        } else {
            if (UI.toString(editPhone).length() == 11) {
                btnSubmit.setSelected(true);
            } else {
                btnSubmit.setSelected(false);
            }
        }
    }

    @OnTextChanged(R.id.edit_code)
    void afterTextChanged1(Editable s) {
        if (TextUtils.isEmpty(UI.toString(editCode))) {
            btnSubmit.setSelected(false);
        } else {
            btnSubmit.setSelected(true);
        }
    }

    private boolean passMatch(String passwd) {
        Pattern p = Pattern.compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$");

        Matcher m = p.matcher(passwd);
        return m.matches();
    }

    @OnTextChanged(R.id.edit_pass_new)
    void afterTextChanged2(Editable s) {
        if (TextUtils.isEmpty(UI.toString(editPassNew))) {
            btnSubmit.setSelected(false);
            btnPassClear.setVisibility(View.GONE);
        } else {
            btnSubmit.setSelected(false);
            btnPassClear.setVisibility(View.VISIBLE);
            btnSubmit.setEnabled(false);
            if (UI.toString(editPassNew).length() >= 6) {
                if (!passMatch(UI.toString(editPassNew))) {
                    txtPassTips.setText("密码必须是由6-20位字母和数字组成");
                    txtPassTips.setTextColor(0xffFF0030);
                } else {
                    btnSubmit.setEnabled(true);
                    txtPassTips.setText("密码由6-20位字母和数字组成，字母需区分大小写");
                    txtPassTips.setTextColor(0xffAAAAAA);
                    btnSubmit.setSelected(true);
                }
            }
        }
    }

    @OnClick({R.id.btn_back, R.id.txt_right, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.txt_right:
                Util.startActivity(this, WechatChatActivity.class);
                break;
            case R.id.btn_submit:
                if (UI.toString(btnSubmit).equals("点击验证")) {
                    if (TextUtils.isEmpty(UI.toString(editPhone))) {
                        ToastUtil.makeText(this, "手机号不能为空");
                        return;
                    }
                    getSmsSend(UI.toString(editPhone));
                } else if (UI.toString(btnSubmit).equals("下一步")) {
                    if (!TextUtils.isEmpty(verify_token)) {
//                        有token的情况
                        if (TextUtils.isEmpty(UI.toString(editPassNew))) {
                            ToastUtil.makeText(this, "密码不能为空");
                            return;
                        }
                        getRegister(verify_token, UI.toString(editPassNew));
                    }else {
                        //                        没有token，正常注册的情况
                        if (TextUtils.isEmpty(UI.toString(editCode))) {
                            ToastUtil.makeText(this, "验证码不能为空");
                            return;
                        }
                        getSmsCheck(self_phone, UI.toString(editCode));
                    }


                } else if (UI.toString(btnSubmit).equals("完成")) {
                    if (TextUtils.isEmpty(UI.toString(editPassNew))) {
                        ToastUtil.makeText(this, "密码不能为空");
                        return;
                    }
                    getRegister(verify_token, UI.toString(editPassNew));
                }
                break;
        }
    }

    @OnClick({R.id.btn_phone_clear, R.id.btn_code_clear, R.id.btn_send_code, R.id.btn_pass_clear, R.id.btn_pass_visible})
    public void onViewClicked1(View view) {
        switch (view.getId()) {
            case R.id.btn_code_clear:
                editCode.setText("");
                break;
            case R.id.btn_phone_clear:
                editPhone.setText("");
                break;
            case R.id.btn_send_code:
                getSmsSend(UI.toString(editPhone));
                break;
            case R.id.btn_pass_clear:
                editPassNew.setText("");
                break;
            case R.id.btn_pass_visible:
                if (!isVisible) {
                    //如果选中，显示密码
                    editPassNew.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    btnPassVisible.setImageResource(R.mipmap.img_eyes_open);
                } else {
                    //否则隐藏密码
                    editPassNew.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    btnPassVisible.setImageResource(R.mipmap.img_eyes_close);
                }
                isVisible = !isVisible;
                break;
        }
    }
}
